#include "GraphScene.h"
#include "GraphicsItems/ClassItem.h"
#include "GraphicsItems/OperationItem.h"
#include <QtGui>
#include "GraphicsItems/Arrow.h"

GraphScene::GraphScene(void)
{
	line = 0;
}

GraphScene::~GraphScene(void)
{
}

void GraphScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
	if (_mode == AddRelation && line)
	{
		QLineF newLine(line->line().p1(), mouseEvent->scenePos());
		line->setLine(newLine);
	}
	else if (_mode == Move)
	{
		QGraphicsScene::mouseMoveEvent(mouseEvent);
	}
}

void GraphScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
	if (mouseEvent->button() == Qt::LeftButton)
	{
		switch (_mode)
		{
		case AddClass:
		case AddOperation:
		{
			QGraphicsTextItem* item = _mode == AddClass
				? (QGraphicsTextItem*)new ClassItem(this)
				: new OperationItem(this);
			addItem(item);
			item->setPos(mouseEvent->scenePos());
			break;
		}
		case AddRelation:
			line = new QGraphicsLineItem(QLineF(
				mouseEvent->scenePos(),	mouseEvent->scenePos()));
			line->setPen(QPen(Qt::gray, 2));
			addItem(line);
			break;
		}
	}
	QGraphicsScene::mousePressEvent(mouseEvent);
}

void GraphScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
	if (line != 0 && _mode == AddRelation)
	{
		QPointF p1 = line->line().p1(),
			p2 = line->line().p2();
		removeItem(line);
		delete line;
		line = 0;

		QGraphicsItem* startGraphicsItem = itemAt(p1);
		QGraphicsItem* endGraphicsItem = itemAt(p2);

		if (startGraphicsItem && endGraphicsItem &&
			startGraphicsItem != endGraphicsItem)
		{
			GraphNodeItem* startItem = (GraphNodeItem *)startGraphicsItem;
			GraphNodeItem* endItem = (GraphNodeItem *)endGraphicsItem;

			Arrow* arrow = new Arrow(this, startItem, endItem);
			addItem(arrow);
			arrow->updatePosition();
		}
	}

	QGraphicsScene::mouseReleaseEvent(mouseEvent);
}
